<?php
/**
 * Created by PhpStorm.
 * User: mr.lee
 * Date: 2018/11/15
 * Time: 12:36 PM
 */

namespace app\api\controller;

use app\common\controller\Deviceobj;
use app\common\controller\FeiePrint;
use app\common\controller\TemplateMsg;
use app\common\model\Agent;
use app\common\model\Merchant;
use app\common\model\Paylog;
use app\common\model\WxOpen;
use Bank\HuifuServer;

class Huifupay extends Pub
{
    public function pay($param, $pays)
    {
        $Merchant = new Merchant();
        $Agent = new Agent();
        $WxOpen = new WxOpen();
        $map['id'] = $param['merchantid'];
        $config = $Merchant->where($map)->find();
        $total_fee = $param['total_fee'];
        $out_trade_no = $this->getorder($param['merchantid']);
        $pays['orderid'] = $out_trade_no;
        $kt = substr($param['auth_code'], 0, 2);
        if ($kt >= 25 && $kt <= 30) {
            $pay_fs = 3;
        } elseif ($kt >= 10 && $kt <= 15) {
            $pay_fs = 2;
        }
        $pays['pay_fs'] = $pay_fs;
        $Paylog = new Paylog();
        $Paylog->save($pays);
        $agent = $Agent->where(array('id' => $config['agent']))->find();
        $users = $WxOpen->where(array('id' => $agent['wx_open_id']))->find();
        $JsonData['appId'] = $users['authorizer_appid'];
        $JsonData['termOrdId'] = $out_trade_no;
        $JsonData['memberId'] = $config['huifu_memberid'];
        $JsonData['merOperId'] = $config['huifu_meroperid'];
        $JsonData['ordAmt'] = number_format($total_fee, 2, ".", "");
        $JsonData['authCode'] = $param['auth_code'];
        $JsonData['apiVersion'] = "2.0.0.1";
        $JsonData['goodsDesc'] = "快捷支付";
        foreach ($JsonData as $k => $v) {
            $JsonData2[$k] = urlencode($v);
        }
        $JsonData2['merPriv'] = array("merNoticeUrl" => "https://" . $_SERVER ['SERVER_NAME'] . "/huifunotify.php/paynotice");
        $JsonData3 = json_encode($JsonData2, JSON_UNESCAPED_UNICODE);
        $HuifuServer = new HuifuServer();
        $data['checkValue'] = $HuifuServer->sign($JsonData3);
        $data['jsonData'] = $JsonData3;
        $data['traceNo'] = "H501-" . date('YmdHis') . rand(100, 999);
        $res = $HuifuServer->b2c_pay($data);
//        return $res;

        $rarr = $this->pay_statu($res, $param['merchantid'], $out_trade_no);
        return $rarr;
    }

    private function pay_statu($param, $id, $orderid, $type = "pay")
    {
        $Paylog = new Paylog();
        $payinfoa = $Paylog->where(['orderid' => $orderid])->find();

        if ($type == "checkpay") {
            $e_param = json_decode($param['jsonData'], true);


            if ($param['respCode'] == "000000") {
                if ($e_param['transStat'] == "S") {
                    $pays['orderno'] = $e_param['outTransId'];
                    $pays['pay_time'] = date('Y-m-d H:i:s', strtotime($e_param['transDate'] . $e_param['transTime']));;
                    $pays['pay_statu'] = 1;
                    $pays['sub_openid'] = isset($e_param['openId']) ? $e_param['openId'] : "";;
                    $pays['openid'] = isset($e_param['subOpenId']) ? $e_param['subOpenId'] : "";
                    $pays['payinfo'] = json_encode($e_param);
                    $pays['price'] = $e_param['transAmt'];
                    $pays['trade_no'] = $e_param['partyOrderId'];
                    $Pub = new Pub();
                    $pays['service_charge'] = $e_param['merFee'];
                    $Paylog->save($pays, array('orderid' => $payinfoa['orderid']));
                    $TemplateMsg = new TemplateMsg();
                    $TemplateMsg->send_tpl('pay', array('merchantid' => $id, 'orderid' => $orderid));
//                    $Deviceobj = new Deviceobj();
//                    $s=$Deviceobj->ylb_sendvoice($orderid);
                    $FeiePrint = new FeiePrint();
                    $FeiePrint->sendprint($orderid);
                    $arrc['return_code'] = "SUCCESS";
                    $arrc['result_code'] = "SUCCESS";

                    $arrc['return_msg'] = "支付成功";
                    $arrc['result_msg'] = "支付成功";
                    $arrc['out_trade_no'] = $e_param['termOrdId'];
                    $arrc['trade_no'] = $e_param['partyOrderId'];;
                    $arrc = $this->getorderinfo($orderid);
                    $Notify=new CreateNotify();
                    $param['out_trade_no']=$orderid;
                    $param['merchantid']=$id;
                    $Notify->pay_notify($param);
                } elseif ($param['respCode'] == "P") {
                    $arrc['return_code'] = "SUCCESS";
                    $arrc['result_code'] = "USERPAYING";
                    $arrc['return_msg'] = "等待用户输入密码";
                    $arrc['result_msg'] = "等待用户输入密码";
                    $arrc['out_trade_no'] = $payinfoa['orderid'];
                    $arrc['trade_no'] = $payinfoa['trade_no'];
                } elseif ($param['respCode'] == "F") {
                    $arrc['return_code'] = "SUCCESS";
                    $arrc['result_code'] = "FAIL";
                    $arrc['return_msg'] = "支付失败";
                    $arrc['result_msg'] = "支付失败";
                }else{
                    $arrc['return_code'] = "SUCCESS";
                    $arrc['result_code'] = "FAIL";
                    $arrc['return_msg'] = "支付失败";
                    $arrc['result_msg'] = "支付失败".$e_param['transStat'];
                }
            } else {
                $arrc['return_code'] = "SUCCESS";
                $arrc['result_code'] = "FAIL";
                $arrc['return_msg'] = "";
                $arrc['result_msg'] = "未知订单状态" . $param['respDesc'];
                $arrc['out_trade_no'] = $payinfoa['orderid'];
                $arrc['trade_no'] = $payinfoa['trade_no'];
            }
        } else {
            $e_param = json_decode($param['jsonData'], true);
            if ($param['respCode'] == "000000") {

                $pays['orderno'] = $e_param['outTransId'];
                $pays['pay_time'] = date('Y-m-d H:i:s', strtotime($e_param['transDate'] . $e_param['transTime']));;
                $pays['pay_statu'] = 1;
                $pays['sub_openid'] = isset($e_param['openid']) ? $e_param['openid'] : "";;
                $pays['openid'] = isset($e_param['sub_openid']) ? $e_param['sub_openid'] : "";
                $pays['payinfo'] = json_encode($e_param);
                $pays['price'] = $e_param['ordAmt'];
                $pays['trade_no'] = $e_param['partyOrderId'];
                $Pub = new Pub();
                $pays['service_charge'] = $e_param['merFee'];
                $Paylog->save($pays, array('orderid' => $payinfoa['orderid']));
                $TemplateMsg = new TemplateMsg();
                $TemplateMsg->send_tpl('pay', array('merchantid' => $id, 'orderid' => $orderid));
                $FeiePrint = new FeiePrint();
                $FeiePrint->sendprint($orderid);
                $arrc['return_code'] = "SUCCESS";
                $arrc['result_code'] = "SUCCESS";

                $arrc['return_msg'] = "支付成功";
                $arrc['result_msg'] = "支付成功";
                $arrc['out_trade_no'] = $e_param['termOrdId'];
                $arrc['trade_no'] = $e_param['partyOrderId'];;
                $arrc = $this->getorderinfo($orderid);

            } elseif ($param['respCode'] == "000199") {
                $arrc['return_code'] = "SUCCESS";
                $arrc['result_code'] = "USERPAYING";
                $arrc['return_msg'] = "等待用户输入密码";
                $arrc['result_msg'] = "等待用户输入密码";
                $arrc['out_trade_no'] = $payinfoa['orderid'];
                $arrc['trade_no'] = $payinfoa['trade_no'];
            } elseif($param['respCode'] == "000198") {
                $arrc['return_code'] = "SUCCESS";
                $arrc['result_code'] = "FAIL";
                $arrc['return_msg'] = "";
                $arrc['result_msg'] = $e_param['bankMessage'];
            } else {

                $arrc['return_code'] = "SUCCESS";
                $arrc['result_code'] = "FAIL";
                $arrc['return_msg'] = "";
                $arrc['result_msg'] = "未知订单状态" . $param['respDesc'];
                $arrc['out_trade_no'] = $payinfoa['orderid'];
                $arrc['trade_no'] = $payinfoa['trade_no'];
            }
        }
        return $arrc;


    }

    public function order_query($orderid)
    {
        $Paylog = new Paylog();
        $orderinfo = $Paylog->where('orderid', $orderid)->find();
        $Merchant = new Merchant();
        $mchinfo = $Merchant->where('id', $orderinfo['mid'])->field('huifu_memberid,huifu_meroperid')->find();
        $JsonData['memberId'] = $mchinfo['huifu_memberid'];
        $JsonData['merOperId'] = $mchinfo['huifu_meroperid'];
        $JsonData['termOrdId'] = $orderinfo['orderid'];
        $JsonData['ordType'] = "1";
        $JsonData['apiVersion'] = "2.0.0.1";
        $JsonData['transDate'] = date('Ymd', $orderinfo['add_time']);
        $JsonData3 = json_encode($JsonData, JSON_UNESCAPED_UNICODE);

        $HuifuServer = new HuifuServer();
        $data['checkValue'] = $HuifuServer->sign($JsonData3);
        $data['jsonData'] = $JsonData3;
        $res = $HuifuServer->order_query($data);
        $rarr=$rarr = $this->pay_statu($res, $orderinfo['mid'], $orderinfo['orderid'],'checkpay');

        return $rarr;
    }
    public function checkpay($param)
    {

        try {
            $orderid = $param['out_trade_no'];

            $rarr = $this->order_query($orderid);
        } catch (\Exception $e) {
            $rarr['return_code'] = "FAIL";
            $rarr['return_msg'] = '系统错误';
            $rarr['result_code'] = 'FAIL';
            $rarr['result_msg'] = '系统错误' . $e->getMessage();
        }

        return $rarr;
    }
//    private function create_paylog($pays)
//    {
//        $out_trade_no = $pays['orderid'];
////        if (isset($param['sub_openid'])) {
////            $sub_openid = $param['sub_openid'];;
////        } elseif (isset($param['buyer_id'])) {
////            $sub_openid = $param['buyer_id'];;
////
////        }
//
//        $data['orderid'] = $out_trade_no;
//        $data['mid'] = $param['id'];
//        $data['openid'] = $sub_openid;
//        $data['pay_statu'] = 0;
//        $data['pay_fs'] = $pay_fs;
//        $data['add_time'] = time();
//        $data['attach'] = isset($param['attach']) ? $param['attach'] : "";
//        $data['price'] = $param['price'];
//        $data['yf_price'] = $param['price'];
//        $Paylog = new Paylog();
//        $Paylog->save($data);
//
//    }
    public function getorder($sh)
    {
        $order = "H" . $sh . "f" . date('YmdHis') . rand(10000, 99999);
        return $order;

    }
}